import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { RestService } from '../../services/rest.service';

import * as _ from 'lodash';

@Component({
  selector: 'app-bindband-dialog',
  templateUrl: './bindband-dialog.component.html',
  styleUrls: ['./bindband-dialog.component.css']
})
export class BindBandDialogComponent implements OnInit {
  devices = [];
  formGroup: FormGroup;
  institution: any;
  person: any;
  url = '';

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<BindBandDialogComponent>,
              private rest: RestService,
              private fb: FormBuilder) {
    this.institution = this.rest.getInstitution();
    this.url = 'data/institution/' + this.institution.id + '/';

    this.person = this.dialogData.person;

    this.formGroup = fb.group({
      name: [
        { value: this.person.personName, disabled: true },
        [ ]
      ],
      device2: [
        { value: this.person.device2Id, disabled: false },
        [ ]
      ]
    });
  }

  submit() {
    const data = {};
    const newDevice2Id = this.formGroup.controls.device2.value;

    if (this.person.device2Id != newDevice2Id) {
      data['device2Id'] = newDevice2Id;
      data['bind2Time'] = new Date().getTime();
      data['unbind2Time'] = 0;
      const index = _.findIndex(this.devices, {deviceId: newDevice2Id});
      if (index > -1) {
        data['device2'] = this.devices[index]['id'];
      }
    }

    this.dialogRef.close(data);
  }

  ngOnInit() {
    this.rest.get(this.url + 'devices').subscribe(data => {
      const devices = data['_embedded']['devices'];
      this.devices = [];
      devices.forEach(device => {
        if (device.personId < 1 || device.deviceId === this.person.device2Id) {
          this.devices.push(device);
        }
      });
    });
  }
}
